package com.example.clock.controlClass;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.example.clock.basicClass.HelpFunc;
import com.example.clock.basicClass.Plan;

import com.example.clock.basicClass.Task;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.AccessControlContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DatabaseHelper extends SQLiteOpenHelper {
    // 数据库名称
    private static final String DATABASE_NAME = "your_database_name";

    // 数据库版本号
    private static final int DATABASE_VERSION = 3;
    private final Context context;

    private SQLiteDatabase database;
//    private DatabaseHelper dbHelper;


    public DatabaseHelper(Context context,Context context1)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context1;
//        dbHelper = new DBHelper(context);
        checkDatabaseDirectory();
    }

    // 打开数据库
    public void open() {
//        database = dbHelper.getWritableDatabase();

//        try {
//            database = dbHelper.getWritableDatabase();
//            Log.d("my", "Database opened successfully");
//        } catch (Exception e) {
//            Log.e("my", "Error opening database: " + e.getMessage());
//            e.printStackTrace();
//        }


        try {
            database = getWritableDatabase();
            Log.d("my", "Database opened successfully");
        } catch (Exception e) {
            Log.e("my", "Error opening database: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 关闭数据库
    public void close() {
//        dbHelper.close();
        if (database != null && database.isOpen()) {
            database.close();
            Log.d("my", "Database closed successfully");
        }

    }



    private void checkDatabaseDirectory() {
        File dbDirectory = context.getDatabasePath(DATABASE_NAME).getParentFile();
        if (!dbDirectory.exists()) {
            dbDirectory.mkdirs(); // 如果目录不存在，则创建目录
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO 创建数据库后，对数据库的操作
        String createBigTags = "CREATE TABLE IF NOT EXISTS BigTags (" +
                "bigTag TEXT PRIMARY KEY)";

        String createPlanTable = "CREATE TABLE IF NOT EXISTS Plans (" +
                "planId TEXT PRIMARY KEY," +
                "planName TEXT," +
                "startDate TEXT," +
                "endDate TEXT," +
                "preTimes INTEGER," +
                "finishTimes INTEGER," +
                "lastTimeByTimes INTEGER," +
                "lastTime INTEGER," +
                "largeTags TEXT," +
                "smallTags TEXT)";

        // Create Tags table
        String createTagsTable = "CREATE TABLE IF NOT EXISTS Tags (" +
                "bigTag TEXT REFERENCES BigTags(bigTag)," +
                "smallTag TEXT)";

        // Create UnlockedSetting table
        String createUnlockedSettingTable = "CREATE TABLE IF NOT EXISTS UnlockedSetting (" +
                "id TEXT PRIMARY KEY,"+
                "forceUnclockTime INTEGER," +
                "normalUnclockedTime INTEGER," +
                "hardUnclockedTime INTEGER," +
                "HellUnclockedTime INTEGER)";

        // Create Task table
        String createTaskTable = "CREATE TABLE IF NOT EXISTS Tasks (" +
                "taskId TEXT PRIMARY KEY," +
                "taskName TEXT," +
                "tips TEXT," +
                "date TEXT," +
                "startTime TEXT," +
                "endTime TEXT," +
                "lastTime INTEGER," +
                "planTime INTEGER," +
                "largeTags TEXT," +
                "smallTags TEXT," +
                "planId TEXT REFERENCES Plans(planId)," +
                "clockedTask INTEGER," +
                "clockedMode INTEGER," +
                "unlocked INTEGER)";

        // Execute the SQL statements
        db.execSQL(createPlanTable);
        db.execSQL(createTagsTable);
        db.execSQL(createUnlockedSettingTable);
        db.execSQL(createTaskTable);
        db.execSQL(createBigTags);

        ContentValues cv = new ContentValues();
        cv.put("id","2023-12-15");
        cv.put("forceUnclockTime",3);
        cv.put("normalUnclockedTime",10);
        cv.put("hardUnclockedTime",20);
        cv.put("hellUnclockedTime",30);
        db.insert("UnlockedSetting",null,cv);

        SqlController.addBigTag(db,"学习");
        SqlController.addSmallTag(db,"学习","写作");
        SqlController.addSmallTag(db,"学习","复习");
        SqlController.addSmallTag(db,"学习","学英语");
        SqlController.addSmallTag(db,"学习","其他");
        SqlController.addBigTag(db,"工作");
        SqlController.addSmallTag(db,"工作","做表格");
        SqlController.addSmallTag(db,"工作","做汇报");
        SqlController.addSmallTag(db,"工作","开会");
        SqlController.addSmallTag(db,"工作","其他");
        SqlController.addBigTag(db,"休息");
        SqlController.addSmallTag(db,"休息","午睡");
        SqlController.addSmallTag(db,"休息","晚睡");
        SqlController.addSmallTag(db,"休息","小憩");
        SqlController.addSmallTag(db,"休息","吃饭");

        SqlController.addBigTag(db,"社交");
        SqlController.addSmallTag(db,"社交","父母");
        SqlController.addSmallTag(db,"社交","朋友");
        SqlController.addSmallTag(db,"社交","同学");
        SqlController.addSmallTag(db,"社交","其他");

            Plan plan1 = new Plan("12","第一个计划","2022-10-1","2023-10-2",15,0,15,15,"学习","写作");
            Plan plan2 = new Plan("12","第er个计划","2023-10-1","2024-10-2",15,2,15,15,"工作","做表格");
            Plan plan3 = new Plan("12","第san计划","2023-10-2","2024-10-2",15,0,15,15,"休息","午睡");
            Plan plan4 = new Plan("3","修改过的个计划","2022-10-1","2025-10-2",15,1,15,15,"社交","晚睡");
            SqlController.addPlan(db,plan1);
            SqlController.addPlan(db,plan2);
            SqlController.addPlan(db,plan3);
            SqlController.addPlan(db,plan4);




        Toast.makeText(context, "Create succeed", Toast.LENGTH_LONG).show();
    }

    public long insertTask(Task task) {
        ContentValues values = new ContentValues();
        values.put("taskId", task.getTaskId());
        values.put("taskName", task.getTaskName());
        values.put("tips", task.getTips());
        values.put("date", task.getDate());
        values.put("startTime", task.getStartTime());
        values.put("endTime", task.getEndTime());
        values.put("lastTime", task.getLastTime());
        values.put("planTime", task.getPlanTime());
        values.put("largeTags", task.getLargeTags());
        values.put("smallTags", task.getSmallTags());
        values.put("planId", task.getPlanId());
        values.put("clockedTask", task.isClockedTask());
        values.put("clockedMode", task.getClockedMode());
        values.put("unlocked", task.getUnlocked());

        return database.insert("tasks", null, values);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);


    }

    public Cursor getAllTasks(String targetDate) {

//        return database.query("tasks", null, null, null, null, null, null);

        String selection = "date = ?";

        // 定义过滤条件的参数
        String[] selectionArgs = {targetDate};

        // 查询符合条件的任务
        return database.query("tasks", null, selection, selectionArgs, null, null, null);

    }

    public void finishLastThing(){
        // 获取当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        String currentTime = dateFormat.format(new Date());

// 构建更新的值
        ContentValues updateValues = new ContentValues();
        updateValues.put("endTime", currentTime);

// 构建查询条件
        String selection = "endTime = ?";
        String[] selectionArgs = { "~~:~~:~~" }; // 替换为你要查找的特定值

// 查询匹配的记录
        Cursor cursor = database.query("tasks", null, selection, selectionArgs, null, null, null);

// 遍历查询结果，逐条更新记录
        if (cursor.moveToFirst()) {
            //先把lasttime传过去
            @SuppressLint("Range") String starttime = cursor.getString(cursor.getColumnIndex("startTime"));
            int lt = HelpFunc.differenceBetweenTime(currentTime,starttime);
            updateValues.put("lastTime",lt);

            do {
                // 获取记录的唯一标识，例如 taskId
                @SuppressLint("Range") String taskId = cursor.getString(cursor.getColumnIndex("taskId"));

                // 更新记录
                int rowsAffected = database.update("tasks", updateValues, "taskId=?", new String[]{taskId});

                //判断task是否完成了plan的次数
                @SuppressLint("Range") String planid = cursor.getString(cursor.getColumnIndex("planId"));
                if(Integer.parseInt(planid) != 0) {
                    boolean finished = false;
                    Plan plan = SqlController.findPlanById(database, planid);
                    if (plan.getLastTimeByTimes() <= lt)
                        finished = true;
                    SqlController.changePlanByTimeAndTimes(database, planid,finished,lt);
                }

                // 打印日志或处理更新结果
                Log.d("my", "Rows affected for task with taskId " + taskId + ": " + rowsAffected);
            } while (cursor.moveToNext());
        }

// 关闭 Cursor
        cursor.close();
    }

    @SuppressLint("Range")
    public Task getLastTask() {
        Task lastTask = null;
        SQLiteDatabase db = this.getReadableDatabase();

        // 构建查询语句
        String query = "SELECT * FROM tasks ORDER BY taskId DESC, startTime DESC LIMIT 1";

        // 执行查询
        Cursor cursor = db.rawQuery(query, null);

        // 处理查询结果
        if (cursor.moveToFirst()) {
            lastTask = new Task();
            lastTask.setTaskId(cursor.getString(cursor.getColumnIndex("taskId")));
            lastTask.setTaskName(cursor.getString(cursor.getColumnIndex("taskName")));
            // 获取其他属性...

            // 关闭Cursor
            cursor.close();
        }

        // 关闭数据库连接
        db.close();

        return lastTask;
    }


}


